package com.wgchao.authmanager.infrastructure.repository;

import com.wgchao.authmanager.domain.model.Operator;
import com.wgchao.authmanager.domain.model.RoleIdentity;
import com.wgchao.authmanager.domain.model.UserRole;
import com.wgchao.authmanager.domain.repository.UserRoleRepository;
import com.wgchao.authmanager.infrastructure.jpa.entity.UserRoleInfo;
import com.wgchao.authmanager.infrastructure.jpa.repository.UserRoleJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UserRoleRepositoryImpl
 * @author: wgchao
 * @createTime: 2020/5/8 2:54 PM
 * @Description: TODO
 */
@Component
public class UserRoleRepositoryImpl implements UserRoleRepository {
    @Autowired
    private UserRoleJpaRepository userRoleJpaRepository;


    @Override
    public void add(UserRole userRole) {
        //删除原有的用户角色对应关系 重新写入
        userRoleJpaRepository.deleteAllByUname(userRole.getUname());
        //重新写入
        if(userRole.getRoleIds()==null || userRole.getRoleIds().isEmpty()){
            return;
        }
        for(RoleIdentity roleId : userRole.getRoleIds()){
            UserRoleInfo userRoleInfo = new UserRoleInfo();
            userRoleInfo.setUname(userRole.getUname());
            userRoleInfo.setAgencyCode(roleId.getAgencyCode());
            userRoleInfo.setRoleName(roleId.getRoleName());
            userRoleInfo.setCreateTime(userRole.getCreator().getOperateTime());
            userRoleInfo.setCreateUser(userRole.getCreator().getUname());
            userRoleInfo = userRoleJpaRepository.save(userRoleInfo);
        }
    }

    @Override
    public void remove(UserRole userRole, String operator) {

    }

    @Override
    public UserRole get(String id) {
        List<UserRoleInfo> userRoleInfos = userRoleJpaRepository.findAllByUname(id);
        if(userRoleInfos==null || userRoleInfos.isEmpty()){
            return null;
        }
        UserRole userRole = new UserRole(id, new ArrayList<>(),
                new Operator(userRoleInfos.get(0).getCreateUser(), userRoleInfos.get(0).getCreateTime()));
        for(UserRoleInfo userRoleInfo : userRoleInfos){
            userRole.getRoleIds().add(new RoleIdentity(userRoleInfo.getAgencyCode(), userRoleInfo.getRoleName()));
        }
        return userRole;
    }
}
